from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from enum import Enum
from . import db

class ProcessStatus(Enum):
    PROCESSING = 'processing'
    COMPLETED = 'completed'
    FAILED = 'failed'

class Knowledge(db.Model):
    __tablename__ = 'knowledges'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), unique=True, nullable=False)
    embedding_model = db.Column(db.String(255), nullable=False)
    collection_name = db.Column(db.String(255), nullable=False, unique=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关联关系
    documents = db.relationship('Document', backref='knowledge', lazy=True)

class Document(db.Model):
    __tablename__ = 'documents'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    knowledge_id = db.Column(db.Integer, db.ForeignKey('knowledges.id'), nullable=False)
    filename = db.Column(db.String(255), nullable=False)
    minio_path = db.Column(db.String(255))
    status = db.Column(db.Enum(ProcessStatus), nullable=False, default=ProcessStatus.PROCESSING)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关联关系
    segments = db.relationship('DocumentSegment', backref='document', lazy=True)

class DocumentSegment(db.Model):
    __tablename__ = 'document_segments'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    document_id = db.Column(db.Integer, db.ForeignKey('documents.id'), nullable=False)
    segment_index = db.Column(db.Integer, nullable=False)
    text = db.Column(db.String(3000), nullable=False)
    chroma_id = db.Column(db.String(255), nullable=False)